const express = require('express');
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');
const { render } = require('./index')
const app = express();

const PORT = 3333;

app.use(express.json());

async function taskCallback({content, taskId, id }) {
  try {
    await axios.post('/callback', { content, taskId, id, ok: !content})
  } catch(e) {
    console.log(e);
  }
 
}

app.post('/start-task', async (req, res) => {
  try {
    const { url, id } = req.body;
    const taskId = uuidv4();
    // 立即返回响应
    res.json({message: '任务已接收，正在处理中...', code: 200, data: { taskId, id }})
    render({
      url, 
      executablePath: '/Users/liudeng/Downloads/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing', 
    }).then(content => {
      // 成功回调
      taskCallback({taskId, id, content})
    }).catch(err => { 
      // 失败回调
      taskCallback({taskId, id})
    })
  } catch(e) {
    res.status(400).json({message: '参数错误', code: 400})
  }
  
})

app.post('/callback', (req, res) => {
  res.status(500)
})


app.listen(PORT, () => {
  console.log(`listening on port ${PORT}`)
})

